<?php
/**
 * api 接口
 */
 
namespace app\api\controller\v1;

use think\Db;
use \think\Controller;
use think\View;
use think\Exception;
use huobi\Huobi;

class CommonController  extends BaseController{


	function _initialize(){
		parent::_initialize();

	}


	function index(){
		set_time_limit(600);
        date_default_timezone_set("Etc/GMT");
        //加载接口
        Vendor("ccxt.ccxt");
        $exchange_class = "\\ccxt\\huobipro";
        $exchange = new $exchange_class();
        $markets = array('ETH/USDT','BTC/USDT');
        if ($exchange->has['fetchTickers']) {
        	$rs = $exchange->fetch_tickers($markets);
            print_r($rs); // all tickers indexed by their symbols
        }
        exit;
	}


	function demo(){
		$markets=input('param.markets/s');
		if($markets) $markets = explode(',',$markets);

		$platform = new Huobi();
		$rs = $platform->fetchTickers($markets);

		$rs = json_decode($rs,true);
		print_r($rs);
		if($rs ){
			$rows = $rs['data'];
			print_r($rows);
		}
		return;
	}




	function  rechargeaddress(){
		if(false==($data=cache('recharge_address'))){
			$app_config = cmf_get_option('app_config');
			$address = $app_config['recharge_address'];
			if(empty($address)){
				return json(['error'=>1,'msg'=>'充值地址未设置,不还不能充值']);
			}
			$data['address'] = $address;
			$qrcode = $app_config['recharge_address_qrcode'];
			if($qrcode) $qrcode = request()->domain().'/upload/'.$qrcode;
			$data['qrcode']  = $qrcode;
			cache('recharge_address',$data);
		}
		return json(['error'=>0,'msg'=>$this->lang['SUCCESS'],'data'=>$data]);
	}



	//余额激活价格和保证金
	function activeprice(){
		$app_config = cmf_get_option('app_config');
		$price = $app_config['quant_startup_min'];
		if($price<=0) $price=100;
		$deposit = $app_config['deposit'];
		if($deposit<=0) $deposit=20;
		return json(['error'=>0,'msg'=>$this->lang['SUCCESS'],'data'=>['price'=>$price,'deposit'=>$deposit]]);


	}




	function  sendcode(){
		$data= input('param.');
		if(!is_phone($data['username']) &&  !is_email($data['username']) ){
			return json(['error'=>1,'msg'=>$this->lang['LOGIN_NAME_ALARM']]);
		}

        $accountType = '';
        $accountType = is_phone($data['username']) ? 'mobile': 'email';

        $code = cmf_get_verification_code($data['username']);
        if (empty($code)) {
        	return json(['error'=>1,'msg'=>$this->lang['CODE_TOO_MORE']]);
        }
		if ($accountType == 'email') {
			$emailTemplate = cmf_get_option('email_template_verification_code');
			$message = htmlspecialchars_decode($emailTemplate['template']);
			$view    = new View();
			$message = $view->display($message, ['code' => $code, 'username' => $data['username']]);
			$subject = empty($emailTemplate['subject']) ? 'ThinkCMF验证码' : $emailTemplate['subject'];
			$result  = cmf_send_email($data['username'], $subject, $message);
			if (empty($result['error'])) {
				cmf_verification_code_log($data['username'], $code);
				return json(['error'=>0,'msg'=>$this->lang['CODE_SEND'].$this->lang['SUCCESS']]);
			}
			return json(['error'=>1,'msg'=>$this->lang['CODE_SEND'].$this->lang['FAIL']]);
		} 


		$param  = ['mobile' => $data['username'], 'code' => $code];
		$result = hook_one("send_mobile_verification_code", $param);
		if ($result !== false && !empty($result['error'])) {
			return json(['error'=>1,'msg'=>$result['message']]);
		}
		if ($result === false) {
			return json(['error'=>1,'msg'=>$this->lang['NO_TEXT_MESSAGE_CONFIG']]);
		}

		cmf_verification_code_log($data['username'], $code);
		if (!empty($result['message'])) {
			return json(['error'=>0,'msg'=>$this->lang['CODE_SEND'].$this->lang['SUCCESS'].$result['message']]);
		}
		return json(['error'=>1,'msg'=>$this->lang['CODE_SEND'].$this->lang['FAIL']]);	
	}



	function login(){
		$data= input('param.');
		if(empty($data['username'])){
			return json(['error'=>1,'msg'=>$this->lang['LOGIN_NAME_INPUT_ALAM']]);
		}
		if(empty($data['password'])){
			return json(['error'=>1,'msg'=>$this->lang['PASSWORD_INPUT_ALAM']]);
		}

		$condition['user_email|mobile|user_login'] = $data['username'];
		$row = Db::name('user')->where($condition)->find();
		if(empty($row)){
			return json(['error'=>1,'msg'=>$this->lang['LOGIN_NAME_NO_EXISTS']]);
		}
		if($row['user_status']==0){
			return json(['error'=>1,'msg'=>$this->lang['LOGIN_NAME_LOCKED']]);
		}
		if($row['user_status']==2){
			return json(['error'=>1,'msg'=>$this->lang['LOGIN_NAME_NO_PASS']]);
		}
		if(!cmf_compare_password($data['password'], $row['user_pass'])){
			return json(['error'=>1,'msg'=>$this->lang['PASSWORD_NOT_RIGHT']]);
		}
		//查找token
		$token = cmf_generate_user_token($row['id']);
		try {
			Db::name('user')->where('id',$row['id'])->update(['last_login_time' => time(), 'last_login_ip' => request()->ip(0,true)]);
			$row['invite_url']=request()->domain(). '/portal/index/invite?invitation_code=' . $row['invitation_code'];
			unset($row['user_pass']);
			unset($row['user_status']);
			return json(['error'=>0,'msg'=>$this->lang['LOGIN'].$this->lang['SUCCESS'],'data'=>$token]);
			//return json(['error'=>0,'msg'=>'登录成功','data'=>$row]);

		} catch (Exception $e) {
			return json(['error'=>1,'msg'=>$this->lang['LOGIN'].$this->lang['FAIL']]);
		}

	}



	function  register(){
		$data= input('param.');
		$app_config = cmf_get_option('app_config');
        if (1==intval($app_config['close_reg'])) {
            return json(['error'=>1,'msg'=>$this->lang['CLOSE'].$this->lang['REGISTER'] ]);
        }



		if(!is_phone($data['username']) &&  !is_email($data['username']) ){
			return json(['error'=>1,'msg'=>$this->lang['LOGIN_NAME_ALARM']]);
		}
		if(empty($data['password'])){
			return json(['error'=>1,'msg'=>$this->lang['PASSWORD_REQUIRED']]);
		}
      
		if(empty($data['verification_code'])){
			return json(['error'=>1,'msg'=>$this->lang['ENTER_VERIFY_CODE'] ]);
		}
		
		$error= cmf_check_verification_code($data['username'], $data['verification_code']);
		if($error){
			return json(['error'=>1,'msg'=>$error]);
		}


		$condition['user_email|mobile|user_login'] = $data['username'];
		$row = Db::name('user')->where($condition)->find();
		if($row){
			return json(['error'=>1,'msg'=>$this->lang['LOGIN_NAME_EXISTS']]);
		}

		        //必须输入邀请码
        if (1==intval($app_config['must_invite_code'])) {
            if(empty($data['invitation_code']) ){
            	return json(['error'=>1,'msg'=>$this->lang['INVITE_CODE_INPUT_ALAM']]);
            }
        }

        $ancestors = [];
        $parent    =[];
        $pid       =0;
        if($data['invitation_code']){
        	$parent = Db::name("user")
				    ->where(['invitation_code' => $data['invitation_code']])
				    ->find();
			if(empty($parent)){
				return json(['error'=>1,'msg'=>$this->lang['INVITE_CODE_ERROR']]);
			}else{
				$ancestors = empty($parent['ancestors'])? [] : json_decode($parent['ancestors'],true);
				array_unshift($ancestors, $parent['id']);
				$pid  = intval($parent['id']);
			}
        }
        Db::startTrans();
        try {
        	if(is_phone($data['username'])){
				$user['mobile']  = $data['username'];
			}else{
				$user['user_email'] = $data['username'];
			}
			$user['avatar']        = '';
	        $user['signature']     = "暂无签名";
	        $user['user_nickname'] = "用户" . strval(mt_rand(10000, 99999));
	        $user['last_login_ip'] = request()->ip(0,true);
	        $user['create_time']   = time();
	        $user['user_status']   = 1;
	        $user['user_type']     = 2;
	        $user['user_pass']     = cmf_password($data['password']);
	        $user['ancestors']     = json_encode($ancestors);
	        $user['parent_user_id']= $pid;
        	$user_id= Db::name('user')->insertGetId($user);

        	//调整直推人数
        	if($pid>0){
        		Db::name('user')->where('id',$pid)->setInc('invitation_count',1);
        	}
        	//调整团队人数
        	if(count($ancestors)>0){
        		Db::name('user')->where(['id'=>['in',$ancestors]])->setInc('group_num',1);
        	}
        	$token = cmf_generate_user_token($user_id);
			Db::commit();
			return json(['error'=>0,'msg'=>$this->lang['REGISTER'].$this->lang['SUCCESS'],'data'=>$token]);

        } catch (Exception $e) {
        	Db::rollback();
        	return json(['error'=>1,'msg'=>$this->lang['REGISTER'].$this->lang['FAIL']]);
        }

	}


	//找回密码
	function  resetpwd(){
		$data= input('param.');
		if(!is_phone($data['username']) &&  !is_email($data['username']) ){
			return json(['error'=>1,'msg'=>$this->lang['LOGIN_NAME_ALARM']]);
		}
		if(empty($data['password'])){
			return json(['error'=>1,'msg'=>$this->lang['PASSWORD_REQUIRED']]);
		}


		if(empty($data['verification_code'])){
			return json(['error'=>1,'msg'=>$this->lang['ENTER_VERIFY_CODE'] ]);
		}

		$error= cmf_check_verification_code($data['username'], $data['verification_code']);
		if($error){
			return json(['error'=>1,'msg'=>$error]);
		}

		$condition['user_email|mobile|user_login'] = $data['username'];
		$row = Db::name('user')->where($condition)->find();
		if(empty($row)){
			return json(['error'=>1,'msg'=>$this->lang['LOGIN_NAME_NO_EXISTS']]);
		}
		//修改密码
		try {
			Db::name("user")->where('id',$row['id'])->update(['user_pass' => cmf_password($data['password'])]);
			return json(['error'=>0,'msg'=>$this->lang['OPERATE'].$this->lang['SUCCESS']]);	
		} catch (Exception $e) {
			return json(['error'=>1,'msg'=>$this->lang['OPERATE'].$this->lang['FAIL']]);	
		}
        
	}



	public function upload()
    {	
    	if($this->request->file('avatar')){
            $file = $this->request->file('avatar');
        }else{
            return '请选择上传文件';
        }
        $custom_path = date('Y/m/d'); // 应用定义的上传目录规则：'Y/md/H/'
        $save_path   = CMF_ROOT .'/public/upload/'. $custom_path;
        $result = $file->validate(['ext'  => 'jpg,jpeg,png','size' => 1024 * 1024])->rule('uniqid')->move($save_path);
        if ($result) {
        	$filename = 'upload/'.$custom_path.'/'.$result->getSaveName();
            $url =  request()->domain().'/'.$filename;
            return json(['error'=>0,'msg'=>$this->lang['UPLOAD'].$this->lang['SUCCESS'],'data'=>['url'=>$url,'filename'=>$filename]]);
        } else {
        	return json(['error'=>0,'msg'=>$this->lang['UPLOAD'].$this->lang['FAIL']]);
         
        }
    }



}